define(['jquery', 'bootstrap', 'backend', 'table', 'form','template'], function ($, undefined, Backend, Table, Form, Template) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'project/index' + location.search,
                    add_url: 'project/add',
                    edit_url: 'project/edit',
                    del_url: 'project/del',
                    multi_url: 'project/multi',
                    import_url: 'project/import',
                    batch_import_url: 'project/batchimport',
                    detail_url: 'project/detail',
                    table: 'project',
                }
            });

            var table = $("#table");
            var projectConfig = Config.projectConfig;
            var tenderTypeList = Config.tenderTypeList;
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                height:700,
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true,formatter: function(value, row, index) {
                            return {
                                disabled: !(Config.childrenAdminIds.indexOf(row.admin_id) > -1)
                            };
                        }},
                        {field: 'id', title: __('Id'),sortable:true},
                        {field: 'project_name', title: __('Project_name'), operate: 'LIKE', formatter:function (value, row, index) {
                            return "<a href='javascript:void(0);' style='color: #4397fd' class='btn-dialog' " +
                                        "data-url='project/detail/ids/"+row.id+"' data-title='项目详情' data-area=[\"100%\",\"100%\"] >" + row.project_name + "</a>";
                        }},
                        {field: 'project_address', title: __('Project_address'), operate: 'LIKE'},
                        {field: 'pricing_date', title: __('Pricing_date'),sortable:true, operate: 'RANGE',datetimeFormat:'YYYY-MM-DD', formatter: Table.api.formatter.datetime, addclass:'datetimerange',},
                        {field: 'tender_type', title: __('Tender_type'), searchList: tenderTypeList, formatter: Table.api.formatter.status},
                        {field: 'project_class', title: __('Project_class'), searchList: projectConfig.project_class, formatter: Table.api.formatter.normal, formatter: function (value, row, index) {
                            return projectConfig.project_class[value] || '-';
                        }},
                        {field: 'project_bulid_cost', title: __('Project_bulid_cost'), operate:'BETWEEN'},
                        {field: 'project_scale', title: __('Project_scale'), operate:'BETWEEN'},
                        // {field: 'square_build_cost', title: __('Square_build_cost'), operate:'BETWEEN'},
                        {field: 'build_unit', title: __('Build_unit')},
                        {field: 'construction_unit', title: __('Construction_unit')},
                        {field: 'structure_type', title: __('Structure_type'), searchList: projectConfig.structure_type, formatter: function (value, row, index) {
                            return projectConfig.structure_type[value] || '-';
                        }},
                        {field: 'build_cost_type', title: __('Build_cost_type'), searchList: projectConfig.build_cost_type, formatter: function (value, row, index) {
                            return projectConfig.build_cost_type[value] || '-';
                        }},
                        {field: 'build_form', title: __('Build_form'), searchList: projectConfig.build_form, formatter: function (value, row, index) {
                            return projectConfig.build_form[value] || '-';
                        }},
                        {field: 'taxation_type', title: __('Taxation_type'), searchList: projectConfig.taxation_type, formatter: function (value, row, index) {
                            return projectConfig.taxation_type[value] || '-';
                        }},
                        {field: 'contract_no', title: __('Contract_no')},
                        // {field: 'start_date', title: __('Start_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        // {field: 'end_date', title: __('End_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        // {field: 'real_start_date', title: __('Real_start_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        // {field: 'real_end_date', title: __('Real_end_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        // {field: 'project_params', title: __('Project_params'), operate: 'LIKE'},
                        // {field: 'pricing_method', title: __('Pricing_method')},
                        // {field: 'pricing_basis', title: __('Pricing_basis')},
                        // {field: 'pricing_inventory', title: __('Pricing_inventory')},
                        // {field: 'senior_editor_date', title: __('Senior_editor_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        // {field: 'quota_days', title: __('Quota_days')},
                        // {field: 'contract_days', title: __('Contract_days')},
                        // {field: 'real_days', title: __('Real_days')},
                        // {field: 'prepared_date', title: __('Prepared_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        // {field: 'prepared_by', title: __('Prepared_by'), operate: 'LIKE'},
                        // {field: 'build_unit', title: __('Build_unit'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'compilation_unit', title: __('Compilation_unit'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'review_unit', title: __('Review_unit'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'contacts', title: __('Contacts'), operate: 'LIKE'},
                        // {field: 'contact_mobile', title: __('Contact_mobile'), operate: 'LIKE'},
                        // {field: 'constact_email', title: __('Constact_email'), operate: 'LIKE'},
                        // {field: 'project_files', title: __('Project_files'), operate: false, formatter: Table.api.formatter.files},
                        {field: 'admin.nickname', title: __('Admin_id')},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        // {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                        buttons: [{
                            name: 'edit',
                            icon: 'fa fa-pencil',
                            title: __('Edit'),
                            extend: 'data-toggle="tooltip" data-container="body"',
                            classname: 'btn btn-xs btn-success btn-editone',
                            visible: function (row) {
                                return Config.childrenAdminIds.indexOf(row.admin_id) > -1;
                            }
                        },{
                            name: 'del',
                            icon: 'fa fa-trash',
                            title: __('Del'),
                            extend: 'data-toggle="tooltip" data-container="body"',
                            classname: 'btn btn-xs btn-danger btn-delone',
                            visible: function (row) {
                                return Config.childrenAdminIds.indexOf(row.admin_id) > -1;
                            }
                        }], formatter: Table.api.formatter.operate}
                    ]
                ]
            });
            $(document).on("click",'#btn-import-xml',function() {
                Fast.api.open($.fn.bootstrapTable.defaults.extend.import_url, "导入项目", {area:["100%","100%"]});
            });
            $(document).on("click",'#btn-import-batch',function() {
                Fast.api.open($.fn.bootstrapTable.defaults.extend.batch_import_url, "批量导入项目", {area:["100%","100%"]});
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'project/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'project_name', title: __('Project_name')},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'project/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'project/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        import: function () {
            // $('[data-toggle="cxselect"]').cxSelect({
            //     selects: ['province', 'city', 'area'],
            // });
            Controller.api.bindevent();
        },
        batchimport: function () {
            Controller.api.bindevent();
        },
        tabledetail    : {
            
            list1: function () {
                //操作日志
                var table1 = $("#operation_list");
                // 初始化表格
                table1.bootstrapTable({
                    url          : 'project_list/getListByProject?id='+Config.idinfo.id,
                    pk           : 'id',
                    sortName     : 'id',
                    sortOrder    : 'asc',
                    toolbar      : "#toolbar_list",
                    height       : 600,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    pagination   : false,
                    // fixedColumns: true,
                    // fixedRightNumber: 1,
                    // fixedNumber: 4,
                    cache:true,
                    striped:false,
                    rowAttributes: function (row, index) {
                        return row.pid == 0 ? {} : {style: "display:none"};
                    },
                    responseHandler:function(res) {
                        $('#listcount').html(res.total > 0 ? '('+res.total+')' : '')
                        return res;
                    },
                    rowStyle: function (row, index) {
                        return {
                            css: {
                                "background-color": 
                                    row.level == 1 ? "#e6f3ff" :       // 一级背景色
                                    row.level == 2 ? "#f0f0f0" :       // 二级背景色 
                                    row.level == 3 ? "#fff3cd" : ""    // 三级背景色
                            }
                        };
                    },
                    columns      : [
                        [
                            {checkbox: true},
                            {field: 'id', title: __('序号'),formatter:function (value,row,index,field) {
                                //row.level
                                return index+1
                            }},
                            {field: 'code', title: __('项目编码')},
                            {field: 'name', title: __('项目名称'), align:'left', cellStyle:function (value,row,index,field) {
                                    return {
                                        css: {
                                            "min-width": "200px",
                                            "white-space": "unset",
                                            "text-overflow": "ellipsis",
                                            "overflow": "hidden",
                                            "max-width":"250px",
                                            'cursor':"pointer",
                                            "background-color": 
                                                row.level == 1 ? "#e6f3ff" :       // 一级背景色
                                                row.level == 2 ? "#f0f0f0" :       // 二级背景色 
                                                row.level == 3 ? "#fff3cd" : ""    // 三级背景色
                                        }
                                    };
                                },
                                formatter: Controller.api.formatter.title, clickToSelect: false
                            },
                            
                            {field: 'description', title: __('项目特征描述'),cellStyle:function (value,row,index,field) {
                                    return {
                                        css: {
                                            "min-width": "200px",
                                            "white-space": "unset",
                                            "text-overflow": "ellipsis",
                                            "overflow": "hidden",
                                            "max-width":"250px",
                                            'cursor':"pointer",
                                            "background-color": 
                                                row.level == 1 ? "#e6f3ff" :       // 一级背景色
                                                row.level == 2 ? "#f0f0f0" :       // 二级背景色 
                                                row.level == 3 ? "#fff3cd" : ""    // 三级背景色
                                        }
                                    };
                                },formatter:function (value,row,index,field) {
                                    var span=document.createElement('span');
                                    span.setAttribute('title',value);
                                    span.innerHTML = value;
                                    return span.outerHTML;
                                }
                            },
                            {field: 'unit', title: __('计量单位')},
                            {field: 'quantity', title: __('工程量'), formatter:function (value,row,index,field) {
                                return parseFloat(value) > 0 ? value : ''
                            }},
                            {field: 'unit_price', title: __('综合单价(元)'), formatter:function (value,row,index,field) {
                                return parseFloat(value) > 0 ? value : ''
                            }},
                            {field: 'total_price', title: __('合价(元)'), formatter:function (value,row,index,field) {
                                return parseFloat(value) > 0 ? value : ''
                            }},
                            {field: 'appraise_price', title: __('暂估价(元)'), formatter:function (value,row,index,field) {
                                return parseFloat(value) > 0 ? value : ''
                            }},
                            {field: 'operate', title: __('Operate'), table: table1, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                        ]
                    ]
                });

                table1.on('post-body.bs.table', function () {
                    const $table = $(this);
                    
                    // 解绑旧事件防止重复绑定
                    $table.off('click', '.btn-node-sub')
                        .on('click', '.btn-node-sub', function(e) {
                            e.stopPropagation();
                            const $btn = $(this);
                            const parentId = $btn.data('id');
                            const isExpanded = $btn.data('shown') || false;
                
                            // 批量操作DOM元素
                            const $childRows = $table.find(`a[data-pid="${parentId}"]`).closest('tr');
                            const $toggleIcon = $btn.find('i.fa');
                            console.log('$childRows:', $childRows.length)
                            // 使用CSS过渡动画
                            $childRows.stop().slideToggle(200, function() {
                                $(this).toggleClass('expanded', !isExpanded);
                            });
                
                            // 图标状态切换
                            $toggleIcon.toggleClass('fa-caret-down', !isExpanded)
                                      .toggleClass('fa-caret-right', isExpanded);
                
                            // 状态标记
                            $btn.data('shown', !isExpanded);
                        });
                });
                
                // 使用Bootstrap原生折叠事件替换自定义事件
                table1.on('show.bs.collapse hide.bs.collapse', '.collapse', function(e) {
                    const $target = $(e.target);
                    const $btn = $target.prev('.btn-node-sub');
                    
                    // 保持图标状态同步
                    $btn.find('i.fa')
                        .toggleClass('fa-caret-down', e.type === 'show')
                        .toggleClass('fa-caret-right', e.type === 'hide');
                });

                // table1.on('post-body.bs.table', function (e, settings, json, xhr) {
                //     //显示隐藏子节点
                //     $(this).on('click', "a.btn-node-sub", function () {
                //         var status = $(this).data("shown") ? true : false;
                //         console.log('length:'+$("a[data-pid='" + $(this).data("id") + "']").length)
                //         $("a[data-pid='" + $(this).data("id") + "']").each(function () {
                //             $(this).closest("tr").toggle(!status);
                //             console.log('a')
                //         });
                //         if (status) {
                //             $("a[data-pid='" + $(this).data("id") + "']").trigger("collapse");
                //         } 
                //         $(this).data("shown", !status);
                //         $("i", this).toggleClass("fa-caret-down").toggleClass("fa-caret-right");
                //         return false;
                //     });
                // });
    
                // //隐藏子节点
                // $(document).on("collapse", ".btn-node-sub[]", function () {
                //     console.log('collapse-length:'+$("i", this).length)
                //     if ($("i", this).length > 0) {
                //         $("a[data-pid='" + $(this).data("id") + "']").trigger("collapse");
                //     }
                //     $("i", this).removeClass("fa-caret-down").addClass("fa-caret-right");
                //     $(this).data("shown", false);
                //     $(this).closest("tr").toggle(false);
                // });
    
                //展开隐藏一级
                $(document.body).on("click", ".btn-toggle", function (e) {
                    $("a[data-id][data-pid][data-pid!=0].disabled").closest("tr").hide();
                    var that = this;
                    var show = $("i", that).hasClass("fa-chevron-down");
                    $("i", that).toggleClass("fa-chevron-down", !show).toggleClass("fa-chevron-up", show);
                    $("a[data-id][data-pid][data-pid!=0]").not('.disabled').closest("tr").toggle(show);
                    $(".btn-node-sub[data-pid=0]").data("shown", show);
                });
    
                //展开隐藏全部
                $(document.body).on("click", ".btn-toggle-all", function (e) {
                    var that = this;
                    var show = $("i", that).hasClass("fa-plus");
                    $("i", that).toggleClass("fa-plus", !show).toggleClass("fa-minus", show);
                    $(".btn-node-sub:not([data-pid=0])").closest("tr").toggle(show);
                    $(".btn-node-sub").data("shown", show);
                    $(".btn-node-sub > i").toggleClass("fa-caret-down", show).toggleClass("fa-caret-right", !show);
                });
                Table.api.bindevent(table1);
            },
            list2: function () {
                //操作日志
                var table2 = $("#operation_rencaiji");
                // 初始化表格
                table2.bootstrapTable({
                    url          : 'project_rencaiji/getListByProject?id='+Config.idinfo.id,
                    pk           : 'id',
                    sortName     : 'id',
                    toolbar      : "#toolbar_rencaiji",
                    height       : 600,
                    operate      : false,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    fixedColumns: true,
                    fixedRightNumber: 1,
                    fixedNumber: 4,
                    responseHandler:function(res) {
                        $('#rencaijicount').html(res.total > 0 ? '('+res.total+')' : '')
                        return res;
                    },
                    columns      : [
                        [
                            {checkbox: true},
                            {field: 'id', title: __('序号'),sortable:true},
                            {field: 'code', title: __('编码')},
                            {field: 'name', title: __('材料设备名称'),cellStyle:function (value,row,index,field) {
                                return {
                                    css: {
                                        "min-width": "100px",
                                        "white-space": "unset",
                                        "text-overflow": "ellipsis",
                                        "overflow": "hidden",
                                        "max-width":"250px",
                                        'cursor':"pointer"
                                    }
                                };
                            }},
                            {field: 'description', title: __('规格型号')},
                            {field: 'unit', title: __('单位')},
                            {field: 'catename', title: __('类别')},
                            {field: 'quantity', title: __('数量')},
                            {field: 'unit_price', title: __('除税市场价(元)')},
                            {field: 'total_price', title: __('除税市场合价(元)')},
                            {field: 'tax', title: __('税率(%)')},
                            {field: 'tax_unit_price', title: __('含税市场价(元)')},
                            {field: 'tax_total_price', title: __('含税市场合价(元)')},
                            {field: 'brandname', title: __('品牌')},
                            {field: 'suppliername', title: __('厂家')},
                            {field: 'price_source', title: __('价格来源')},
                            {field: 'operate', title: __('Operate'), table: table2, events: Table.api.events.operate, formatter: Table.api.formatter.operate}

                        ]
                    ]
                });
                Table.api.bindevent(table2);
            },
            list3: function () {
                //操作日志
                var table3 = $("#operation_material");
                // 初始化表格
                table3.bootstrapTable({
                    url          : 'project_assess/getListByProject?id='+Config.idinfo.id,
                    pk           : 'id',
                    sortName     : 'id',
                    toolbar      : "#toolbar_assess",
                    height       : 600,
                    operate      : false,
                    commonSearch : false,
                    search       : true,
                    visible      : false,
                    showColumns  : true,
                    showExport   : true,
                    showToggle   : false,
                    fixedColumns: true,
                    fixedRightNumber: 1,
                    fixedNumber: 4,
                    responseHandler:function(res) {
                        $('#assesscount').html(res.total > 0 ? '('+res.total+')' : '')
                        return res;
                    },
                    columns      : [
                        [
                            {checkbox: true},
                            {field: 'code', title: __('编码')},
                            {field: 'name', title: __('名称'),cellStyle:function (value,row,index,field) {
                                return {
                                    css: {
                                        "min-width": "100px",
                                        "white-space": "unset",
                                        "text-overflow": "ellipsis",
                                        "overflow": "hidden",
                                        "max-width":"250px",
                                        'cursor':"pointer"
                                    }
                                };
                            }},
                            {field: 'description', title: __('规格型号')},
                            {field: 'unit', title: __('单位')},
                            {field: 'catename', title: __('类别')},
                            {field: 'quantity', title: __('数量')},
                            {field: 'tax', title: __('进项税率(%)')},
                            {field: 'reference_price', title: __('评审参考价(元)')},
                            {field: 'unit_price', title: __('市场单价(元)')},
                            {field: 'total_price', title: __('合价(元)')},
                            {field: 'operate', title: __('Operate'), table: table3, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                        ]
                    ]
                });
                Table.api.bindevent(table3);
            },
            basic:function (){

            }
        },
        detail: function () {
            
            $('.stafflist').popover({
                placement : 'bottom',
                trigger : 'hover'
            });
            //绑定事件
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var panel = $($(this).attr("href"));
                if (panel.length > 0) {
                    var control = 'project_detail'
                    if (panel.attr("id") == 'list1') {
                        control = 'project_list'
                    } else if (panel.attr("id") == 'list2') {
                        control = 'project_rencaiji'
                    }else if (panel.attr("id") == 'list3') {
                        control = 'project_assess'
                    }
                    // 关键修复1：解绑整个工具栏的点击事件
                    var toolbar = panel.find(".toolbar");
                    toolbar.off('click', '.btn-add,#btn-import-list,#btn-import-rencaiji'); 

                    // 关键修复2：彻底销毁表格及关联事件
                    var table = panel.find(".bootstrap-table");
                    if (table.length > 0) {
                        table.bootstrapTable('destroy');
                        table.data('bootstrap.table', null); // 清除缓存
                    }
                    // 初始化表格参数配置
                    Table.api.init({
                        extend: {
                            index_url: control+'/getListByProject' + location.search,
                            add_url: control+'/add?project_id='+Config.idinfo.id,
                            edit_url: control+'/edit',
                            del_url: control+'/del',
                            multi_url: control+'/multi',
                            import_url: control+'/import?project_id='+Config.idinfo.id,
                            detail_url: control+'/detail',
                            table: control,
                        }
                    });
                    
                    Controller.tabledetail[panel.attr("id")].call(this);
                    // $(this).on('click', function (e) {
                    //     $($(this).attr("href")).find(".btn-refresh").trigger("click");
                    // });
                }
                //移除绑定的事件
                // $(this).unbind('shown.bs.tab');
            });
            $(document).on("click",'#btn-import-list',function() {
                Fast.api.open("project_list/import?project_id="+Config.idinfo.id, "导入清单", {area:["100%","100%"]});
            });
            $(document).on("click",'#btn-import-rencaiji',function() {
                Fast.api.open("project_rencaiji/import?project_id="+Config.idinfo.id, "导入人材机", {area:["100%","100%"]});
            });
            $(document).on('click','#edits',function () {
                var id=$('#ids').val();
                Fast.api.open("project/edit?ids="+id, "项目编辑",{
                    shadeClose: false,
                    shade: false,
                    maxmin: false,
                    moveOut: false,
                    scrollbars:false,
                    area:["95%","95%"],
                    callback:function(value){
                        location.reload();
                    },
                });

            })
            
            //必须默认触发shown.bs.tab事件
            $('ul.nav-tabs li.active a[data-toggle="tab"]').trigger("shown.bs.tab");
            Controller.api.bindevent();
        },
        
        api: {
            formatter: {
                title: function (value, row, index) {
                    value = value.toString().replace(/(&|&amp;)nbsp;/g, '&nbsp;');
                    var caret = row.haschild == 1 ? '<i class="fa fa-caret-right"></i>' : '';
                    value = value.indexOf("&nbsp;") > -1 ? value.replace(/(.*)&nbsp;/, "$1" + caret) : caret + value;

                    value = row.haschild == 0 ? "<span class='text-muted'>" + value + "</span>" : value;
                    return '<a href="javascript:;" data-index="'+index+'" data-id="' + row.id + '" data-pid="' + row.pid + '" class="'
                        + (row.haschild == 1 ? 'text-primary' : 'disabled') + ' btn-node-sub" data-shown="false">' + value + '</a>';
                },
            },
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
                $(document).on('change', '#c-pricing_method', function () {
                    var val = $(this).val();
                    if (val == '2') {
                        $('#c-pricing_inventory').val(0).attr('disabled', true);
                    } else {
                        $('#c-pricing_inventory').attr('disabled', false);
                    }
                })
                
                let originalData = []; // 用于存储原始数据
                let batchtimes = 0;
                let curtimes = 0;
                let lastrow = 0;
                let currentIndex = 0;
                let totalFiles = 0;
                $("#c-file").change(function () {
                    var file = $(this).val();
                    if (file) {
                        var that = this
                        that.layerIndex =layer.load(0,{ shade: 0.3 });
                        $.ajax({
                            url: "project/import_preview",
                            data: {file: file},
                            type: "post",
                            complete: function(){
                                layer.close(that.layerIndex);
                            },
                            success: function (res) {
                                if (res.code == 1) {
                                    originalData = res.data.data;
                                    batchtimes = res.data.batchtimes;
                                    // 调用模板渲染（方案1：直接渲染）
                                    // 结构化数据处理
                                    const renderData = {
                                        project_info: res.data.project_data || {},
                                        project_assess: res.data.project_assess || [],
                                        project_rencaiji: res.data.project_rencaiji || [],
                                        items: res.data.data || []
                                    };
                                    // 带错误捕获的模板渲染
                                    try {
                                        const html = Template('projecttpl', renderData);
                                        $('#wechat').empty().html(html);
                                        $('ul.nav-tabs li.active a[data-toggle="tab"]').trigger("shown.bs.tab");
                                        Form.api.bindevent($("form[role=form]"));
                                    } catch (e) {
                                        console.error('模板渲染错误:', e);
                                        Toastr.error('数据解析失败');
                                    }
                                } else {
                                    layer.msg(res.msg);
                                    return false;
                                }
                            }
                        });
                    }
                });
                var submit = function(form, success, error, submit) {
                    if (form.size() === 0) {
                        Toastr.error("表单未初始化完成,无法提交");
                        return false;
                    }
                    if (typeof submit === 'function') {
                        if (false === submit.call(form, success, error)) {
                            return false;
                        }
                    }
                    var type = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
                    type = type && (type === 'GET' || type === 'POST') ? type : 'GET';
                    var url = form.attr("action");
                    url = url ? url : location.href;
                    // 调整 serialize 方法以收集修改过的数据
                    var file = form.find("input[name=file]");
                    // 构建最终的提交数据
                    var params = {curtimes, currentIndex};
                    // 修复当存在多选项元素时提交的 BUG
                    var multipleList = $("[name$='[]']", form);
                    if (multipleList.size() > 0) {
                        var postFields = form.serializeArray().map(function (obj) {
                            return obj.name;
                        });
                        $.each(multipleList, function (i, j) {
                            if (postFields.indexOf($(this).prop("name")) < 0) {
                                params[$(this).prop("name")] = '';
                            }
                        });
                    }
                    params = form.serialize() + (Object.keys(params).length > 0 ? '&' + $.param(params) : '')
                    // 调用 Ajax 请求方法
                    // 返回一个新的Promise对象
                    return new Promise(function(resolve, reject) {
                        Fast.api.ajax({
                            type: type,
                            url: url,
                            data: params,
                            dataType: 'json',
                            complete: function (xhr) {
                                var token = xhr.getResponseHeader('__token__');
                                if (token) {
                                    $("input[name='__token__']").val(token);
                                }
                            }
                        }, function (data, ret) {
                            $('.form-group', form).removeClass('has-feedback has-success has-error');
                            if (data && typeof data === 'object') {
                                // 刷新客户端 token
                                if (typeof data.token !== 'undefined') {
                                    $("input[name='__token__']").val(data.token);
                                }
                                // 调用客户端事件
                                if (typeof data.callback !== 'undefined' && typeof data.callback === 'function') {
                                    data.callback.call(form, data);
                                }
                            }
                            if (typeof success === 'function') {
                                if (false === success.call(form, data, ret)) {
                                    return false;
                                }
                            }
                            resolve(ret); // 解析Promise
                        }, function (data, ret) {
                            if (data && typeof data === 'object' && typeof data.token !== 'undefined') {
                                $("input[name='__token__']").val(data.token);
                            }
                            if (typeof error === 'function') {
                                if (false === error.call(form, data, ret)) {
                                    return false;
                                }
                            }
                            reject(ret); // 拒绝Promise
                        });
                        return true;
                    });
                }
                $('#import-submit').click(function () {
                    var that = this,
                    form = $('#import-form'),
                    submitBtn = $(".layer-footer [type=submit]", form);
                    submitBtn.addClass("disabled");
                    async function submitForm(i) {
                        curtimes = i;
                        try {
                            const rets = await submit(form, function(data, ret){
                                if (ret.code == 1) {
                                    
                                }
                                if ((i + 1) === batchtimes) {
                                    submitBtn.removeClass("disabled");
                                    // 提示及关闭当前窗口
                                    var msg = ret.hasOwnProperty("msg") && ret.msg !== "" ? ret.msg : __('Operation completed');
                                    parent.Toastr.success(msg);
                                    parent.$(".btn-refresh").trigger("click");
                                    var index = parent.Layer.getFrameIndex(window.name);
                                    parent.Layer.close(index);
                                }
                            }, function(data, ret){
                                if ((i + 1) === batchtimes) {
                                    submitBtn.removeClass("disabled");
                                }
                            });
                            // 如果需要根据`ret`做进一步处理
                            // console.log('Submit result:', rets);
                        } catch (error) {
                            // 处理错误情况
                            console.error('Error submitting form:', error);
                        }
                    }
                    
                    (async function processNext() {
                        for (let i = 0; i < batchtimes; i++) {
                            await submitForm(i); // 等待当前提交完成
                        }
                    })();
                    
                    return false
                })

                // Layui.use('element', function(){
                    $('#batch-import-submit').click(function () {
                        let files = $('#c-batch_files').val().split(',').filter(Boolean);
                        if(files.length === 0){
                            toastr.error('请先上传文件');
                            return false;
                        }
                        totalFiles = files.length;
                        // var element = layui.element;
                        // element.progress('demo', '50%')
                        var that = this,
                        form = $('#import-batch-form'),
                        submitBtn = $(".layer-footer [type=submit]", form);
                        submitBtn.addClass("disabled");
                        async function submitForm(i) {
                            currentIndex = i;
                            try {
                                const rets = await submit(form, function(data, ret){
                                    if ((i + 1) === totalFiles) {
                                        // element.progress('demo', '100%')
                                        submitBtn.removeClass("disabled");
                                        // 提示及关闭当前窗口
                                        var msg = ret.hasOwnProperty("msg") && ret.msg !== "" ? ret.msg : __('Operation completed');
                                        parent.Toastr.success(msg);
                                        parent.$(".btn-refresh").trigger("click");
                                        var index = parent.Layer.getFrameIndex(window.name);
                                        parent.Layer.close(index);
                                    } else {
                                        console.log('currentIndex:', currentIndex);
                                        // element.progress('demo', (i+1) / totalFiles * 100 + '%')
                                        // parent.Toastr.success(`正在导入第${i+1}个文件`);
                                    }
                                }, function(data, ret){
                                    if ((i + 1) === totalFiles) {
                                        submitBtn.removeClass("disabled");
                                    }
                                });
                                // 如果需要根据`ret`做进一步处理
                                console.log('Submit result:', rets);
                                return;
                            } catch (error) {
                                // 处理错误情况
                                console.error('Error submitting form:', error);
                            }
                        }
                        
                        (async function processNext() {
                            for (let i = 0; i < totalFiles; i++) {
                                await submitForm(i); // 等待当前提交完成
                            }
                        })();
                        
                        return false
                    });
                // })
            }
        }
    };
    return Controller;
});
